import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Task } from '../../pages/home/task';
import 'rxjs/add/operator/map';

/*
  Generated class for the HttpDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpDataProvider {

  private readonly baseUrl: string = 'https://api2.bmob.cn/1';
  private readonly httpOptions : Object = {
    headers: new HttpHeaders({
      'X-Bmob-Application-Id' : '32aa15579db672f82f75bca86f9e851c',
      'X-Bmob-REST-API-Key' : '9c43935200311654af91a2c17a6f3238',
      'Content-Type' : 'application/json',
    })
  };

  constructor(public http: HttpClient) {
    console.log('获取HTTP数据服务加载..');
  }
  

  /**
   * 获取待办事项列表
   * @returns {Observable<Task[]>} 待办事项列表数据集合
   */
  getTaskList(): Observable<Task[]>{
    return this.http.get<Task[]>(`${this.baseUrl}/classes/ToDoList`,
    this.httpOptions).map(data => data["results"]);//利用map把集合映射一下

  }
  /**
   * 获取指定待办事项
   * @param objectId 
   * @returns  {Observable<Task>} 待办事项
   */
  getTask(objectId: string):Observable<Task>{
    return this.http.get<Task>(`${this.baseUrl}/classes/ToDoList/${objectId}`,
    this.httpOptions);//利用map把集合映射一下
  }

  /**
   * 新增待办事项
   * @param task 
   * 
   */
  addTask(task:Task): Observable<Task>{
    let _task ={title:task.title, status:task.status, description:task.description};
    return this.http.post<Task>(`${this.baseUrl}/classes/ToDoList`,
    _task,this.httpOptions)
  }


   /**
   * 更新指定事项列表
   * @returns {Observable<Task[]>}响应结果
   */
  updateTask(task : Task):Observable<Task>{
    let _task ={title:task.title, status:task.status, description:task.description};
    return this.http.put<Task>(`${this.baseUrl}/classes/ToDoList/${task.objectId}`,
    _task,this.httpOptions).map(data => data["results"]);
  }

  
   /**
   * 删除指定事项列表
   * @returns {Observable<{}>}响应结果
   */
  deleteTask(task:Task): Observable<{}>{
    return this.http.delete(`${this.baseUrl}/classes/ToDoList/${task.objectId}`,
    this.httpOptions).map(data => data["results"]);
  }




}
